export default {
    data() {
        return {
            focusedIndex: -1,
        }
    },
    watch: {
        popShown() {
            this.focusedIndex = -1
        }
    },
    mounted() {
        this.addEventListener()
    },
    unmounted() {
        this.removeEventListener()
    },
    methods: {
        addEventListener() {
            window.document.addEventListener('keydown', this.onDocumentKeydown)
        },
        removeEventListener() {
            window.document.removeEventListener('keydown', this.onDocumentKeydown)
        },
        onDocumentKeydown(e) {
            if (!this.popShown) {
                return
            }
            if (e.keyCode == 38) {
                let children = this.getPopEl().children
                let focusedIndex = this.focusedIndex
                for (let i = focusedIndex - 1; i >= 0; i--) {
                    if (!this.getDisabledFunc(this.items[i])) {
                        children[i].focus()
                        this.focusedIndex = i
                        break
                    }
                }
            }
            else if (e.keyCode == 40) {
                let children = this.getPopEl().children
                let focusedIndex = this.focusedIndex
                for (let i = focusedIndex + 1; i < children.length; i++) {
                    if (!this.getDisabledFunc(this.items[i])) {
                        children[i].focus()
                        this.focusedIndex = i
                        break
                    }
                }
            }
        },
        getPopEl() {
            return this.$refs.popup.getPopEl()
        },
    }
}